<template>
    <div class="borrow-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入借阅信息查询" clearable @clear="handleClearSearch"
                class="search-input" />
        </div>

        <!-- 借阅记录表 -->
        <el-table :data="borrowRecords" stripe border>
            <el-table-column prop="borrow_id" label="借阅ID" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="journal_name" label="期刊名称" />
            <el-table-column prop="year" label="年" />
            <el-table-column prop="volume" label="卷" />
            <el-table-column prop="issue" label="期" />
            <el-table-column prop="borrow_date" label="借阅日期" />
            <el-table-column prop="return_date" label="归还日期" />
            <el-table-column label="状态">
                <template #default="{ row }">
                    <el-tag :type="statusTagMap[row.status] || 'info'">
                        {{ statusOptions[row.status] || '未知状态' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="openStatusDialog(row)">
                        修改状态
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row.borrow_id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />

        <!-- 状态修改弹窗 -->
        <el-dialog title="修改借阅状态" v-model="statusDialogVisible" width="400px" :close-on-click-modal="false">
            <el-form :model="currentRecord">
                <el-form-item label="当前状态" label-width="100px">
                    <el-tag :type="statusTagMap[currentRecord.status] || 'info'">
                        {{ statusOptions[currentRecord.status] || '未知状态' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="选择新状态" label-width="100px">
                    <el-select v-model="currentRecord.newStatus" placeholder="选择状态" style="width: 100%;">
                        <el-option v-for="(statusLabel, statusValue) in statusOptions" :key="statusValue"
                            :label="statusLabel" :value="statusValue" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="statusDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveBorrowStatus">
                    保存
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { borrowApi } from '@/request/apiService';
import { ElMessageBox } from 'element-plus';

const borrowRecords = ref([]); // 存储借阅记录
const search = ref(''); // 搜索关键字
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页记录数
const total = ref(0); // 总记录数

// 借阅状态选项和颜色映射
const statusOptions = {
    locked: '锁定中',
    borrowed: '已借阅',
    returned: '已归还',
    cancelled: '已取消',
};

const statusTagMap = {
    locked: 'info',
    borrowed: 'success',
    returned: 'primary',
    cancelled: 'danger',
};

// 弹窗状态和当前记录
const statusDialogVisible = ref(false); // 控制状态弹窗的显示
const currentRecord = ref({
    borrow_id: null,
    status: '',
    newStatus: '',
});

// 获取借阅记录列表
const fetchBorrowRecords = async () => {
    try {
        const { data, total: totalCount } = await borrowApi.getBorrowList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
        });
        borrowRecords.value = data;
        total.value = totalCount;
    } catch (error) {
        console.error('获取借阅记录失败', error);
    }
};

// 打开状态修改弹窗
const openStatusDialog = (record) => {
    currentRecord.value = {
        borrow_id: record.borrow_id, // 使用借阅ID
        status: record.status,
        newStatus: record.status, // 默认选中当前状态
    };
    statusDialogVisible.value = true;
};

// 保存修改后的借阅状态
const saveBorrowStatus = async () => {
    const { borrow_id, status, newStatus } = currentRecord.value;

    if (status === newStatus) {
        ElMessage.warning('状态未发生改变，无需保存');
        return;
    }

    try {
        await borrowApi.updateBorrowStatus({ borrow_id, status: newStatus });
        statusDialogVisible.value = false;
        await fetchBorrowRecords();
    } catch (error) {
        console.error('借阅状态更新失败:', error);
    }
};

// 删除借阅记录
const handleDelete = (borrow_id) => {
    ElMessageBox.confirm('此操作将永久删除该借阅记录, 是否继续?', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await borrowApi.deleteBorrowRecord({ borrow_id });
                await fetchBorrowRecords();
            } catch (error) {
                console.error('删除借阅记录失败:', error);
            }
        })
        .catch(() => console.log('删除操作已取消'));
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchBorrowRecords();
};

// 分页改变时触发
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchBorrowRecords();
};

// 页面加载时，获取借阅数据
onMounted(fetchBorrowRecords);

// 监听搜索变化自动获取数据
watch(search, fetchBorrowRecords);
</script>

<style scoped>
.borrow-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}

.status-select {
    margin-top: 8px;
    width: 100%;
}
</style>
